package com.siwei.mes.service.experiment.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.siwei.mes.common.query.PageQuery;
import com.siwei.mes.entity.ShxhSynchronizedata;
import com.siwei.mes.entity.UploadLaboratoryEntity;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentSupplyTask;
import com.siwei.mes.entity.sync.tc.SupplyTask;
import com.siwei.mes.entity.sync.tc.Waybill;
import com.siwei.mes.mapper.ShxhSynchronizedataMapper;
import com.siwei.mes.mapper.experiment.ExperimentMapper;
import com.siwei.mes.mapper.experiment.ExperimentSupplyTaskMapper;
import com.siwei.mes.mapper.experiment.ExperimentWaybillMapper;
import com.siwei.mes.mapper.syncTc.SupplyTaskMapper;
import com.siwei.mes.service.experiment.ExperimentSupplyTaskService;
import com.siwei.mes.sync.config.SyncProcessorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * 试验台账与供货任务关系(ExperimentSupplyTask)表服务实现类
 *
 * @author makejava
 * @since 2024-05-28 23:00:03
 */
@Slf4j
@Service
public class ExperimentSupplyTaskServiceImpl implements ExperimentSupplyTaskService {
    @Resource
    private ExperimentSupplyTaskMapper experimentSupplyTaskMapper;
    @Resource
    private ExperimentWaybillMapper experimentWaybillMapper;
    @Resource
    private ExperimentMapper experimentMapper;
    @Resource
    private SupplyTaskMapper supplyTaskMapper;
    @Resource
    private SyncProcessorService syncProcessorService;
    @Resource
    private ShxhSynchronizedataMapper shxhSynchronizedataMapper;

    @Override
    public Long create(ExperimentSupplyTask entity) {
        entity.setCreateTime(new Date());
        entity.setReadTime(null);
        experimentSupplyTaskMapper.insertSelective(entity);
        /**这里新增任务单的关联关系 给对应试验委托的isNewTask改为1*/
        log.info(this.getClass().getName() + "新增任务单给对应isNewTask修改为1");
        experimentMapper.updateIsNewTask(entity.getExperimentId(), 1);

        /**推送到协会，这里新增任务单 状态为自动上传*/
        /**这里判断是否已经上传到协会，如果没有上传到协会就不推送*/
        ShxhSynchronizedata shxhSynchronizedata = shxhSynchronizedataMapper.selectByExperimentIdOne(entity.getExperimentId());
        if (shxhSynchronizedata != null && shxhSynchronizedata.getSampleId() != null) {
            log.info(this.getClass().getName() + "新增任务单之后，推送协会！");
            syncProcessorService.submitRequest(new UploadLaboratoryEntity().setExperimentId(Collections.singletonList(String.valueOf(entity.getExperimentId()))).setUploadState(1));
        }
        return entity.getId();
    }

    @Override
    public void update(ExperimentSupplyTask entity) {
        ExperimentSupplyTask experimentSupplyTask = experimentSupplyTaskMapper.selectByPrimaryKey(entity.getId());
        assertTrue(experimentSupplyTask == null, "试验台账与供货任务关系信息不存在");
        experimentSupplyTaskMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void delete(Long id) {
        ExperimentSupplyTask experimentSupplyTask = experimentSupplyTaskMapper.selectByPrimaryKey(id);
        assertTrue(experimentSupplyTask == null, "试验台账与供货任务关系信息不存在");
        experimentSupplyTaskMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo<ExperimentSupplyTask> getPage(PageQuery<ExperimentSupplyTask, ExperimentSupplyTask> query) {
        ExperimentSupplyTask searchParam = query.getParams();
        return PageHelper.startPage(query.getPageNum(), query.getPageSize())
                .doSelectPageInfo(() -> experimentSupplyTaskMapper.getList(searchParam));
    }

    @Override
    public ExperimentSupplyTask loadById(Long id) {
        return experimentSupplyTaskMapper.loadById(id);
    }

    @Override
    public List<ExperimentSupplyTask> getAll(ExperimentSupplyTask entity) {
        return experimentSupplyTaskMapper.getList(entity);
    }

    @Override
    public List<SupplyTask> selectByExperimentId(Long experimentId) {
        List<SupplyTask> taskList = experimentSupplyTaskMapper.selectByExperimentId(experimentId);
        for (SupplyTask supplyTask : taskList) {
            /**获取这个任务单在这个试验委托中的代表数量是多少*/
            BigDecimal behalfNumber = experimentWaybillMapper.selectByBehalfNumber(supplyTask.getSupplyTaskId(), experimentId);
            supplyTask.setBehalfNumber(behalfNumber);

            /**这里采购数量等于代表数量*/
            supplyTask.setSignQuantity(behalfNumber);

            if (supplyTask.getSignQuantity() == null) {
                supplyTask.setSignQuantity(supplyTask.getSupplyPlanQuantity());
            }
        }
        return taskList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByExperimentIdAndSupplyTaskId(Long experimentId, Long supplyTaskId) {
        log.info("开始删除原材料试验委托与任务关系，试验委托id:【{}】,任务id:【{}】", experimentId, supplyTaskId);

        /**根据supplyTaskId查询原材料供货任务*/
        SupplyTask supplyTask = supplyTaskMapper.selectByTaskId(supplyTaskId);
        assertTrue(supplyTask == null, "原材料供货任务不存在");

        List<ExperimentSupplyTask> list = experimentSupplyTaskMapper.getList(new ExperimentSupplyTask().setExperimentId(experimentId).setSupplyTaskId(supplyTask.getId()));

        for (ExperimentSupplyTask task : list) {
            experimentSupplyTaskMapper.deleteByPrimaryKey(task.getId());
        }

        List<Waybill> waybills = experimentWaybillMapper.selectByExperimentIdAndTask(experimentId, supplyTaskId);
        for (Waybill waybill : waybills) {
            log.info("开始删除运单信息，试验委托id:【{}】,运单id:【{}】", experimentId, waybill.getId());
            experimentWaybillMapper.deleteByExperimentIdAndWaybillId(experimentId, waybill.getId());
        }

        /**修改这个试验台账的代表数量 == 所有跟这个试验台账相关的运单签收数量之和*/
        List<Waybill> waybillList = experimentWaybillMapper.selectByExperimentId(experimentId);
        Double behalfNumberSum = null;
        if (!waybillList.isEmpty()) {
            behalfNumberSum = waybillList.stream().map(Waybill::getBehalfNumber).reduce((double) 0, Double::sum);
            Experiment experiment = new Experiment();
            experiment.setId(experimentId);
            experiment.setBehalfNumber(behalfNumberSum);
            experiment.init(false);
            experimentMapper.updateByPrimaryKeySelective(experiment);
        }


        /**这里判断是否已经上传到协会，如果没有上传到协会就不推送*/
        ShxhSynchronizedata shxhSynchronizedata = shxhSynchronizedataMapper.selectByExperimentIdOne(experimentId);
        if (shxhSynchronizedata != null && shxhSynchronizedata.getSampleId() != null) {
            log.info("删除原材料试验委托和任务关系，推送到协会处理代表数量。");
            List<String> experimentIdList = new ArrayList<>();
            experimentIdList.add(experimentId.toString());
            /**推送到协会*/
            syncProcessorService.submitRequest(new UploadLaboratoryEntity().setExperimentId(experimentIdList).setUploadState(0));
        }
    }
}
